/*
 * @Description: 
 * @Author: paddies
 * @Date: 2024-07-31 03:27:02
 * @LastEditors: paddies
 * @LastEditTime: 2024-11-19 08:36:01
 * @FilePath: /luntai-user-app/Users/paddies/Desktop/code/A-team/luntai/shared_components/lib/build-page2/buildPage.dart
 */
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:shared_components/build-common/buildCommon.dart';
import 'package:shared_components/build-image/buildImage.dart';
import 'package:shared_components/build-page2/controller.dart';
import 'package:shared_components/utils/index.dart';

class buildPage2 extends StatefulWidget {
  final bool centerTitle;
  final String title;
  final bool hasTab;
  final int tabIndex;
  final bool isOpen;

  final List tabList;

  final List list;

  final Function()? actionsSlot;

  final Function(dynamic, String)? itemSlot;
  final Function? onChangeTab;
  final Function? onRefresh;
  final Function? onNextPage;

  const buildPage2(
      {super.key,
      this.centerTitle = true,
      this.hasTab = true,
      this.itemSlot,
      this.list = const [],
      this.isOpen = false,
      this.actionsSlot,
      this.onChangeTab,
      this.onRefresh,
      this.onNextPage,
      this.title = '标题',
      this.tabIndex = 0,
      this.tabList = const []});
  @override
  State<buildPage2> createState() => _buildPageState();
}

class _buildPageState extends State<buildPage2> {
  final buildPagePageController2 controller =
      Get.put(buildPagePageController2());
  ScrollController scrollController = ScrollController();

  @override
  void initState() {
    //参数异常检测
    paramsVerify();
    controller.initConfig(
        tabList: widget.tabList, tabIndex: widget.tabIndex, list: widget.list);
    // 添加列表滑动监听
    scrollController.addListener(() {
      // 滑动距离
      var dis = scrollController.position.maxScrollExtent -
          scrollController.position.pixels;
      // 当滑动到底部不足 300 并且没有加载数据时，加载更多
      // 也可以根据临界值，是否允许下拉刷新以及下拉加载更多
      if (dis == 0) {
        JhCommonUtils.debounce(() {
          print("===继续加载====");
          paramsVerify();
          if (widget.onNextPage != null) {
            widget.onNextPage!();
          }
          // controller.nextPage();
        }, 100);
        // _loadData(loadMore: true);
      }
    });
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final double statusBarHeight = MediaQuery.of(context).padding.top;
    var actions = [];
    if (widget.actionsSlot != null) {
      actions = (widget.actionsSlot!() as List);
    }
    if (!widget.isOpen) {
      return Obx(() => Scaffold(
          appBar: AppBar(
            centerTitle: widget.centerTitle,
            scrolledUnderElevation: 0.0,
            iconTheme: const IconThemeData(
              color: Colors.black, //修改颜色
            ),
            title: Text(
              widget.title,
              style: const TextStyle(color: Colors.black),
            ),
            actions: [
              ...actions,
            ],
            backgroundColor: Colors.white,
          ),
          backgroundColor: const Color(0xfff6f6f6),
          body: SizedBox(
            width: double.infinity,
            height: double.infinity,
            child: Column(
              children: [
                //有 tab
                Visibility(
                    visible: widget.hasTab,
                    child: Expanded(
                      child: hasTabPanel(),
                    )),

                Visibility(
                    visible: !widget.hasTab,
                    child: Expanded(
                      child: noTabPanel(),
                    ))
              ],
            ),
          )));
    }
    return Obx(() => SizedBox(
          width: double.infinity,
          height: double.infinity,
          child: Column(
            children: [
              //有 tab
              Visibility(
                  visible: widget.hasTab,
                  child: Expanded(
                    child: hasTabPanel(),
                  )),

              Visibility(
                  visible: !widget.hasTab,
                  child: Expanded(
                    child: noTabPanel(),
                  ))
              // navSlot ?? const SizedBox(),
            ],
          ),
        ));
  }

  paramsVerify() async {
    //参数异常检测
    if (widget.hasTab && widget.onChangeTab == null) {
      await EasyLoading.dismiss();
      EasyLoading.showError("缺少onChangeTab事件");
    }
  }

  onRefresh() {
    print("下拉刷新");
    paramsVerify();
    if (widget.onRefresh != null) {
      widget.onRefresh!();
    }
  }

  onChangeTab(int index) {
    controller.state.tabIndex.value = index;
    var tabIndex = index;
    if (widget.onChangeTab != null) {
      widget.onChangeTab!(tabIndex);
    }
  }

  Widget hasTabPanel() {
    return Container(
      width: double.infinity,
      height: double.infinity,
      padding: EdgeInsets.only(left: 5, right: 5),
      // color: Colors.yellow,
      child: Column(children: [
        Container(
            width: double.infinity,
            height: 45,
            color: Colors.white,
            child: Row(
              children: controller.state.tabList.asMap().keys.map((index) {
                var fontColor = const Color(0xff666666);
                if (controller.state.tabIndex.value == index) {
                  fontColor = controller.state.activeColor;
                }
                return Expanded(
                    child: Stack(alignment: Alignment.center, children: [
                  Container(
                    height: double.infinity,
                    // color: Colors.red,
                    width: 70,
                    child: GestureDetector(
                        onTap: () {
                          paramsVerify();
                          onChangeTab(index);
                          onRefresh();
                        },
                        child: Container(
                          alignment: Alignment.center,
                          width: double.infinity,
                          margin: EdgeInsets.only(left: 5, right: 5),
                          // decoration: BoxDecoration(
                          //     color: Color(0xfffdf1f1),
                          //     borderRadius:
                          //         BorderRadius.all(Radius.circular(8))),
                          // height: double.infinity,
                          child: Stack(
                            alignment: Alignment.center,
                            children: [
                              Container(
                                width: 70,
                                height: 35,
                                alignment: Alignment.center,
                                padding: EdgeInsets.only(top: 3, bottom: 3),
                                decoration: BoxDecoration(
                                    color:
                                        controller.state.tabIndex.value == index
                                            ? Color(0xfffdf1f1)
                                            : Color(0xfff7f7f7),
                                    borderRadius:
                                        BorderRadius.all(Radius.circular(8))),
                                child: Text(
                                  showText(controller.state.tabList.value[index]
                                      .value["name"]),
                                  style: TextStyle(
                                      fontSize: 14,
                                      color: fontColor,
                                      fontWeight: FontWeight.w500),
                                ),
                              ),
                              // if (controller.state.tabIndex.value == index)
                              //   Container(
                              //     margin: const EdgeInsets.only(top: 40),
                              //     width: 30,
                              //     height: 5,
                              //     decoration: BoxDecoration(
                              //         borderRadius: BorderRadius.all(
                              //             Radius.circular(20.0)), //圆角
                              //         gradient: LinearGradient(
                              //             begin:
                              //                 Alignment.topLeft, //渐变开始于上面的中间开始
                              //             end: Alignment.topRight, //渐变结束于下面的中间
                              //             colors: [
                              //               controller.state.activeColor,
                              //               controller.state.activeColor,
                              //             ] //开始颜色和结束颜色])),
                              //             )),
                              //   )
                            ],
                          ),
                        )),
                  ),
                  Visibility(
                    visible: controller.state.tabList.value[index]
                                .value["showCount"] ==
                            true &&
                        controller.state.tabList.value[index].value["count"] !=
                            0,
                    child: Padding(
                      padding: EdgeInsets.only(right: 2, top: 0),
                      child: Align(
                        alignment: Alignment.topRight,
                        child: Container(
                          width: 30,
                          height: 15,
                          decoration: BoxDecoration(
                            color: Colors.red,
                            borderRadius:
                                BorderRadius.all(Radius.circular(8.0)), //圆角
                          ),
                          alignment: Alignment.center,
                          child: Text(
                            showText(controller
                                .state.tabList.value[index].value["count"]),

                            // showText(controller.getAllCountName()),
                            style: TextStyle(fontSize: 10, color: Colors.white),
                          ),
                        ),
                      ),
                    ),
                  )
                ]
                        // children:
                        ));
              }).toList(),
            )),
        Expanded(
            child: Container(
          width: double.infinity,
          height: double.infinity,
          // color: Colors.blue,
          child: RefreshIndicator(
              onRefresh: () async {
                onRefresh();
              },
              child: Container(
                  width: double.infinity,
                  height: double.infinity,
                  // color: Colors.red,
                  child: SingleChildScrollView(
                      physics: AlwaysScrollableScrollPhysics(),
                      controller: scrollController,
                      child:
                          // Container(
                          //   width: double.infinity,
                          //   height: double.infinity,
                          //   color: Colors.green,
                          // child:
                          Column(
                        children: [
                          Visibility(
                              visible: (controller.state.tabList.value as List)
                                      .length >
                                  0,
                              child: Column(
                                children: [
                                  pageEmpty(),
                                  ...(getNowItemList()).map((e) {
                                    if (widget.itemSlot == null) {
                                      return Container();
                                    }
                                    var code = "";
                                    var tabList =
                                        controller.state.tabList.value;
                                    var tabIndex =
                                        controller.state.tabIndex.value;

                                    if (widget.hasTab && tabList.isNotEmpty) {
                                      code = controller.state.tabList.value[
                                              controller.state.tabIndex
                                                  .value]["state"] ??
                                          "";
                                    }

                                    return widget.itemSlot!(e, code);
                                  }).toList()
                                ],
                              ))
                        ],
                      )
                      // Text(showText(tabList[_activeTab.value]["list"])),
                      // ),
                      // child: ,
                      ))),
        ))
      ]),
    );
  }

  Widget noTabPanel() {
    return SizedBox(
      width: double.infinity,
      height: double.infinity,
      child: RefreshIndicator(
          onRefresh: () async {
            onRefresh();
          },
          child: Container(
              width: double.infinity,
              height: double.infinity,
              // color: Colors.red,
              child: SingleChildScrollView(
                physics: AlwaysScrollableScrollPhysics(),
                controller: scrollController,
                child: Column(
                  children: [
                    pageEmpty(),
                    // Visibility(
                    //     visible: getNowItemList().length > 0,
                    //     child: Column(
                    //       children: [
                    ...getNowItemList().map((element) {
                      if (widget.itemSlot == null) {
                        return Container();
                      }
                      // return Text("111");
                      return widget.itemSlot!(element, "");
                    }).toList()
                    //       ],
                    //     ))
                  ],
                ),
              ))),
    );
  }

  Widget pageEmpty() {
    return Visibility(
      visible: (getNowItemList()).length == 0,
      child: Padding(
          padding: const EdgeInsets.only(top: 100),
          child: SizedBox(
              width: 180,
              height: 180,
              child: buildImage(
                  url: "assets/images/common/empty.png",
                  fit: BoxFit.scaleDown))),
    );
  }

  List getNowItemList() {
    var res = [];

    if (widget.hasTab) {
      var tabIndex = controller.state.tabIndex.value;
      var tabList = controller.state.tabList.value;
      if (tabList.isNotEmpty) {
        res = (controller.state.tabList.value[tabIndex]["list"] as List);
      }
    } else {
      res = controller.state.list.value;
    }

    return res;
  }
}
